<?php

namespace app\shop\controller\api;

use app\ApiController;
use app\distribution\model\DistributionJcLog;
use app\distribution\model\DistributionLog;
use app\distribution\model\DividendAwardModel;
use app\distribution\model\DividendModel;
use app\member\model\AccountModel;
use app\member\model\UsersLevelApplyModel;
use app\member\model\UsersModel;
use app\shop\model\OrderGoodsModel;
use app\shop\model\OrderModel;
use app\shop\model\SlideModel;
use app\shop\model\GoodsModel;
use app\shop\model\NavMenuModel;
use distribution\base\Dividend;
use think\Db;
use think\Exception;

class Index extends ApiController
{

    public function getJcList()
    {
        //$list =UsersLevelApplyModel::where("1=1")->select();
        $additional_setapply = $this->userInfo['additional_setapply'];
        //$additional_div = $this->userInfo['additional_div'];
        if($additional_setapply != 0){

             $res = Db::table('distribution_log')->select();
             if(!empty($res)){
                 $list = Db::table('users_level_apply')
                ->alias(['users_level_apply'=>' level','distribution_log'=>'dislog'])
                ->join('distribution_log',' level.level_id = dislog.jc_id')
                ->where('dislog.user_id','=',$this->userInfo['user_id'])
                ->whereOr('level.level_id','in',$additional_setapply)
                //->group('level.level_id')
                ->select();
             }else{
                 $list =UsersLevelApplyModel::where("level_id","in",$additional_setapply)->select();
             }

        }else{


            $list = Db::table('users_level_apply')
            ->alias(['users_level_apply'=>' level','distribution_log'=>'dislog'])
            ->join('distribution_log',' level.level_id = dislog.jc_id')
            ->where('dislog.user_id','=',$this->userInfo['user_id'])
            ->group('level.level_id')
            ->select();


        }



        //echo Db::table('users_level_apply')->getLastSql();

        return $this->success('','',$list);
    }
    public function Income(){
        $id =input('id');
        if(empty($id)){
            return $this->error("参数错误");
        }
        $where =[
            'jc_log.jc_id'=>$id,
            'jc_log.stage'=>date('Ym'),
        ];
        $list =(new DistributionJcLog())->alias('jc_log')->where($where)->join('shop_goods g','g.goods_id=jc_log.goods_id')
            ->field('jc_log.*,goods_name')
            ->select();

        return $this->success('','',$list);

        /*
        $id =input('id');
        if(empty($id)){
            return $this->error("参数错误");
        }
        $jc =UsersLevelApplyModel::where(['level_id'=>$id])->find();
        $datemonth = intval(date('m'));
        $where =[
            'jc_id'=>$id,
            'user_id'=>$this->userInfo['user_id'],
            'stage'=>date("Y$datemonth"),
        ];

        $user = UsersModel::where(['user_id' => $this->userInfo['user_id']])->find();
        $amount = $jc['total_amount'] / $jc['num'];
        $pushCount = UsersModel::where(['role_id' => $jc['push_level'], 'pid' =>$this->userInfo['user_id']])->field('user_id')->count();
        $num = $pushCount / $jc['push_num'];
        try {
            $additional_div = json_decode($user['additional_div'], true);
            $additional_div = $additional_div[$jc['level_id']]['value'];
        } catch (Exception $exception) {
            $additional_div=0;
        }
        $num = intval($additional_div + $num);
        $divAmount = bcmul($amount, $num);
        $wherejc =[
            'jc_log.jc_id'=>$id,
            'jc_log.stage'=>date('Ym'),
        ];
        $list =(new DistributionJcLog())->alias('jc_log')->where($wherejc)->join('shop_goods g','g.goods_id=jc_log.goods_id')
            ->field('jc_log.*,goods_name')
            ->select();

        unset($where['stage']);
        $total_amount =DistributionLog::where($where)->sum('total_amount');

        $wheretotal =[
            'jc_id'=>$id,
            'user_id'=>$this->userInfo['user_id'],
            //'stage'=>date("Y$datemonth"),
        ];
        $alltotal_amount =DistributionLog::where($wheretotal)->sum('total_amount');//累计分红

        $yujitotal_amount = $this->getfenhongamountbuuid($this->userInfo['user_id']);  //预计分红

        $wherefenshu =[
            'jc_id'=>$id,
            'user_id'=>$this->userInfo['user_id'],
            //'stage'=>date("Y$datemonth"),
        ];
        $fenshutotal_amount =DistributionLog::where($wherefenshu)->sum('num');//累计份数

        //份数
        $additional_div = json_decode($this->userInfo['additional_div'],true);
        if($additional_div || !empty($additional_div)){
            $nums = 0;
            foreach ($additional_div as $k=>$v){
                foreach ($v as $kk=>$vv){
                    $nums += $vv;
                }
            }
        }else{
            $nums = 0;
        }




        $data =['list'=>$list,'divAmount'=>$total_amount,'total_amount'=>$alltotal_amount,'yujitotal_amount'=>$yujitotal_amount,'fenshu'=>$nums,'info'=>$jc];


        return $this->success('','',$data);
        */
    }
    public function getJcInfo(){
        $id =input('id');
        if(empty($id)){
            return $this->error("参数错误");
        }
        $jc =UsersLevelApplyModel::where(['level_id'=>$id])->find();
        $datemonth = intval(date('m')) -1;
        $where =[
            'jc_id'=>$id,
            'user_id'=>$this->userInfo['user_id'],
            'stage'=>date("Y$datemonth"),
        ];
        $user = UsersModel::where(['user_id' => $this->userInfo['user_id']])->find();
        $amount = $jc['total_amount'] / $jc['num'];
        $pushCount = UsersModel::where(['role_id' => $jc['push_level'], 'pid' =>$this->userInfo['user_id']])->field('user_id')->count();
        $num = $pushCount / $jc['push_num'];
        try {
            $additional_div = json_decode($user['additional_div'], true);
            $additional_div = $additional_div[$jc['level_id']]['value'];
        } catch (Exception $exception) {
            $additional_div=0;
        }
        $num = intval($additional_div + $num);
        $divAmount = bcmul($amount, $num);
        $list =DistributionLog::where($where)->select();

        unset($where['stage']);
        $total_amount =DistributionLog::where($where)->sum('total_amount');
        $wheretotal =[
            'jc_id'=>$id,
            'user_id'=>$this->userInfo['user_id'],
            //'stage'=>date("Y$datemonth"),
        ];
        $alltotal_amount = round(DistributionLog::where($wheretotal)->sum('total_amount'),2);//累计分红

        $danyuedatemonth = intval(date('m'));

        $yujitotal_amount = round($this->getfenhongamountbuuid($this->userInfo['user_id']),2);  //预计分红

        $total_amount = round(DistributionLog::where($where)->sum('total_amount'),2);
        $wherefenshu =[
            'jc_id'=>$id,
            'user_id'=>$this->userInfo['user_id'],
            //'stage'=>date("Y$datemonth"),
        ];
        $fenshutotal_amount =DistributionLog::where($wherefenshu)->sum('num');//累计份数

        //后台设置附件份数
        $jcs = UsersLevelApplyModel::where("level_id=".$id)->select();


        $fepushCount = UsersModel::where(['role_id' => 1, 'pid' => $this->userInfo['user_id']])->field('user_id')->count();
        $nums = floor($fepushCount / $jcs[0]['zhituidailibyjige']);  //获得几份份额
        $num = intval($nums*$jcs[0]['zhituidailibyjifen']);

        $additional_div = json_decode($this->userInfo['additional_div'], true);

        $additional_div = intval($additional_div[$id]['value']);



        if($additional_div || !empty($additional_div)){

            $numss = $additional_div+$num;
        }else{
            $numss = $num;
        }


        //计算份额份数
        /*
        if($additional_div || !empty($additional_div)){
            $nums = 0;
            foreach ($additional_div as $k=>$v){
                foreach ($v as $kk=>$vv){
                    $nums += $vv;
                }
            }
        }else{
            $nums = 0;
        }
        */



        $data =['list'=>$list,'divAmount'=>$yujitotal_amount,'total_amount'=>$alltotal_amount,'yujitotal_amount'=>$yujitotal_amount,'fenshu'=>$numss,'info'=>$jc];
        return $this->success('','',$data);
    }

    public function getfenhongamountbuuid($user_id)
    {

        $stage =date('Y').(intval(date('m')));

        $jcs = UsersLevelApplyModel::where("num", '>', 0)->select();
        $DistributionLogModel = new DistributionLog();
        foreach ($jcs as $key => $jc) {
            $user = UsersModel::where(['user_id' => $user_id])->find();
            $amount = $jc['total_amount'] / $jc['num'];

            $totalJoinNum = 0;
            $totalCopies = 0;
            $issueAmount = 0;


            $additional_div = json_decode($user['additional_div'], true);
            $additional_div = intval($additional_div[$jc['level_id']]['value']);



            $pushCount = UsersModel::where(['role_id' => $jc['push_level'], 'pid' => $user_id])->field('user_id')->count();
            $num = $pushCount / $jc['push_num'];


            $num = intval($additional_div + $num);

            if ($num <= 0) {
                return 0;
            }
            //$divAmount = bcmul($amount, $num);
            $divAmount = round($amount*$num,2);


            $totalCopies += $num;
            $totalJoinNum++;
            $issueAmount += $divAmount;
            //

            return $issueAmount;
        }



    }

    public function rubfk()
    {


            $upUser = UsersModel::where(['user_id' => 29945])->find();
            rubQr();die;
            if ($upUser['role_id'] == 3 || $upUser['role_id'] == 0) {
                //$pid = 0;
                do {
                    //if (empty($upUser['pid'])) break;
                    $parentId=$upUser['pid'];

                    $upUser = UsersModel::where(['user_id' => $upUser['pid'], 'role_id' => 1])
                        ->field('role_id,user_id,pid')->find();
                    if(!empty($upUser['pid'])){
                        $parentId = $upUser['user_id'];
                    }
                } while ($parentId > 0);
            }
            die;

        $orderInfo = OrderModel::where(['order_sn'=>2023022447314])->find();
        halt((new OrderModel())->distribution($orderInfo, 'add'));
        //halt((new OrderModel())->distribution($orderInfo, 'add'));


        $userMode = new UsersModel();
        $parentId = 29944;
        $goods = GoodsModel::find(38);
        $goods['award_value'] = json_decode($goods['award_value'], true);
        $dailicount = 0;

        do {
            $nowLevel++;
            $userInfo = $userMode->info($parentId); //获取会员信息
            $parentId = $userInfo['pid'];
            if (empty($goods['award_value'][$userInfo['role_id']]['num'][1])) continue;
            $val = $goods['award_value'][$userInfo['role_id']]['num'][1];

            if ($userInfo['role']['level'] == 1) {
                echo "会员积分" . $val . '<br>';
            } else if ($userInfo['role']['level'] == 2) {
                echo "代理" . $val . '<br>';
                $dailicount++;
            } else if ($userInfo['role']['level'] == 3) {
                $jc = 0;
                if ($dailicount > 0) {
                    $jc = empty($goods['award_value'][1]['num'][1]) ? 0 : $goods['award_value'][1]['num'][1];
                }
                $val = $val - intval($jc);
                echo "老板" . $val . '<br>';
            }
        } while ($parentId > 0);


        die;
        $orderInfo = OrderModel::find(120);
        dump((new OrderModel())->distribution($orderInfo, 'pay'));
        halt((new OrderModel())->distribution($orderInfo, 'add'));
        die;
        $user = UsersModel::where('user_id', 29936)->find();
        if (!empty($user) && !empty($user['pid'])) {
            $upUser = UsersModel::where(['user_id' => $user['pid']])->find();
            if ($upUser['role_id'] == 3 || $upUser['role_id'] == 0) {
                $pid = 0;
                do {

                    if (empty($upUser['pid'])) {
                        break;
                    }
                    $upUser = UsersModel::where(['user_id' => $upUser['pid'], 'role_id' => 1])
                        ->field('role_id,user_id,pid')->find();

                    if (!empty($upUser)) {
                        $pid = $upUser['user_id'];
                    }
                } while ($pid == 0);
                halt(UsersModel::where(['user_id' => $pid])->find());
            }
        }
    }

    public function fenhong()
    {
        $key = input('key');
        if ($key !== 'fQ5dF8tA3xF6dE0q') die;
        $stage =date('Y').(intval(date('m')) -1);
        //echo $stage;
        $execute = Db::table('distribution_jc_execute_log')->where('stage',$stage)->count();
        if ($execute) {
            echo "已执行" . PHP_EOL;
            die;
        }
        $jcs = UsersLevelApplyModel::where("num", '>', 0)->select();
        $DistributionLogModel = new DistributionLog();
        foreach ($jcs as $key => $jc) {
            $users = UsersModel::select();
            $amount = $jc['total_amount'] / $jc['num'];
            $totalJoinNum = 0;
            $totalCopies = 0;
            $issueAmount = 0;
            foreach ($users as $user) {
                try {
                    $additional_div = json_decode($user['additional_div'], true);
                    $additional_div = intval($additional_div[$jc['level_id']]['value']);
                } catch (Exception $exception) {
                    continue;
                }
                if(empty($additional_div) && $user['role_id']!==$jc['own_level']){
                    continue;
                }
                $pushCount = UsersModel::where(['role_id' => $jc['push_level'], 'pid' => $user['user_id']])->field('user_id')->count();
                $num = $pushCount / $jc['push_num'];

                $num = intval($additional_div + $num);
                if ($num <= 0) continue;
                $divAmount = bcmul($amount, $num);
                $data = [
                    'jc_id' => $jc['level_id'],
                    'user_id' => $user['user_id'],
                    'num' => $num,
                    'stage' => $stage,
                    'total_amount' => $divAmount,
                    'additional' => empty($additional_div)?0:$additional_div,
                    'createtime' => time(),
                ];

                echo '用户：' . $user['nick_name'] . '  data:' . json_encode($data) . PHP_EOL;
                if($divAmount > 0){
                    $distrijunfenres = $DistributionLogModel->insert($data);
                }

                $AccountModel = new AccountModel();
                $changedata['change_desc'] = $jc['jc_name']."：奖金池分红：用户ID".$user['user_id'].",分红金额".$divAmount."元。";
                $changedata['change_type'] = 10;
                $changedata['by_id'] = 1;
                $changedata['from_uid'] = $user['user_id'];
                $changedata['balance_money'] = $divAmount;
                $changedata['bean_value'] = 0;
                $changedata['total_dividend'] = $divAmount;
                $changedata['md5log'] = $jc['jc_name']."：奖金池分红：用户ID".$user['user_id'].",分红金额:".$divAmount."元。";
                if($distrijunfenres && $divAmount > 0){
                    $AccountModel->change($changedata, $user['user_id'], false);
                }
                $totalCopies += $num;
                $totalJoinNum++;
                $issueAmount += $divAmount;
                //
            }

            $logData = [
                'total_amount' => $jc['total_amount'],
                'issue_amount' => $issueAmount,
                'total_copies' => $totalCopies,
                'total_join_num' => $totalJoinNum,
                'create_time' => time(),
                'stage' => $stage,
            ];
            $jc->save(['total_amount' => 0]);
            Db::table('distribution_jc_execute_log')->insert($logData);
            echo '奖池：' . $jc['jc_name'] . '  data:' . json_encode($logData) . PHP_EOL;
        }
        echo "执行完成" . PHP_EOL;
        die;


//        $goodsList = (new OrderGoodsModel)->where('order_id', 118)->select()->toArray();
//        halt($goodsList);
//        die;
//        $orderInfo = OrderModel::find(118);
//        halt((new OrderModel())->distribution($orderInfo, 'add'));
        //test script
        //分红开始
//        $orderInfo = OrderModel::find(76);
//        halt((new OrderModel())->distribution($orderInfo, 'add'));
//        $changedata['change_desc'] = '购物分返现';
//        $changedata['change_type'] = 3;
//        $changedata['integral_money'] = 100;
//        $res = (new AccountModel())->change($changedata, 29921, false);
//        halt($res);
    }



    public function newfenhong()
    {
        $key = input('key');
        if ($key !== 'fQ5dF8tA3xF6d000') die;
        $stage =date('Y').(intval(date('m')) -1);
        $AccountModel = new AccountModel();
        //echo $stage;
        $execute = Db::table('distribution_jc_execute_log')->where('stage',$stage)->count();
        if ($execute) {
            echo "已执行" . PHP_EOL;
            die;
        }
        $where[] = ["total_amount",'>',100];
        $jcs = UsersLevelApplyModel::where($where)->select();

        $DistributionLogModel = new DistributionLog();
        $junfen_danfenamount = 0;   //均分单份金额多少
        $gongxianzhi_danfenamount = 0; //贡献值单份金额多少
        $fene_danfenamount = 0;// 份额单份金额多少
        $manzuIds = '';
        $manzugxIds = '';
        $manzufeIds = '';
        $allfeneamount = 0;
        $gongzhiallamount = 0;
        $alljunfenamount = 0;

//        $list = Db::name('distribution_jc_log')->where([])->select();
//        foreach ($list as $value){
//            $user_id = Db::name('shop_order_info')->where('order_id',$value['order_id'])->value('user_id');
//            Db::name('distribution_jc_log')->where('id',$value['id'])->update(['user_id' => $user_id]);
//        }
//        exit;

        foreach ($jcs as $key => $jc) {

            //获取后台设置的奖池用户
            $shezhiUser = $this->getUserByadditional();
            $ids = '';
//            foreach ($shezhiUser as $k => $v){
//                $jiangchiid = $v['additional_setapply'];
//                $jiangchiidarr = explode(',',$jiangchiid);
//                if(in_array($jc['level_id'],$jiangchiidarr)){
//                    $ids .= $v['user_id'].',';
//                }
//                //dump($ids);
//            }
//            $ids = rtrim($ids,',');  //后台设置的奖金池用户
            //获取后台设置的奖池用户end

            $users = UsersModel::where('additional_setapply',$jc['level_id'])->select();

            $totalamountss = $jc['total_amount'];
            //均分的总金额
            $junfen_totalamount = floor($jc['total_amount']*($jc['junfenbili']/100));
            //贡献的总金额
            $gongxian_totalamount = floor($jc['total_amount']*($jc['gongzhibili']/100));
            //份额的总金额
            $gongxianfe_totalamount = floor($jc['total_amount']*($jc['fenebili']/100));

            //均分分红
            if($jc['is_junfen'] == 1){

                if($junfen_totalamount > 10) {   //均分金额大于10才循环
                    foreach ($users as $user) {

                        //直推几个代理
                        $pushCount = UsersModel::where(['role_id' => 1, 'pid' => $user['user_id']])->field('user_id')->count(); // 统计自己下面的直推代理数
                        $zhitui_daili_num = floor($pushCount);  //升级条件 直推几个代理

                        //满足条件则
                        if ($zhitui_daili_num >= $jc['zhituidailinum']) {
                            //团队代理数getUserTuanduidailinum
                            $tuanduires = $this->getUserTuanduidailinum($user['user_id']);

                            if ($tuanduires >= $jc['tuanduidailinum']) {
                                //echo $user['user_id']."<br>";
                                $manzuIds .= $user['user_id'] . ',';
                                //echo $jc['zhituidailinum'].'----';
                            }

                        }
                    }

                    //均分的所有用户
                    $junfenUserList = rtrim($manzuIds.$ids,',');
                    $junfenUserListarr = explode(',',$junfenUserList);

                    $totaljunfenUser = count($junfenUserListarr);
                    $totalUser = count($junfenUserListarr);

                    //平均分每个人多少钱
                    $junfen_danfenamount = floor($junfen_totalamount/$totaljunfenUser);
                    $junfen_alldanfenamount = $junfen_danfenamount-($junfen_danfenamount*0.05); //扣除5%


                    foreach ($junfenUserListarr as $k=>$v){

                        $data = [
                            'jc_id' => $jc['level_id'],
                            'user_id' => $v,
                            'num' => 1,
                            'stage' => $stage,
                            'total_amount' => $junfen_alldanfenamount,
                            'additional' => 0,
                            'createtime' => time(),
                            'fenhongname' => $jc['jc_name'].'-均分分红',
                        ];

                        echo '用户：' . $this->getUserNamebyuid($v) . '  data:' . json_encode($data) . PHP_EOL;
                        if($junfen_danfenamount > 0){
                            $distrijunfenres = $DistributionLogModel->insert($data);
                            if($distrijunfenres){
                                $alljunfenamount += $junfen_danfenamount;

                                $changedata['change_desc'] = $stage.$jc['jc_name']."：奖金池-均分分红：用户ID".$v."，分红金额:".$junfen_danfenamount."元。";
                                $changedata['change_type'] = 40;
                                $changedata['by_id'] = 1;
                                $changedata['from_uid'] = $v;
                                $changedata['balance_money'] = $junfen_danfenamount;
                                $changedata['bean_value'] = 0;
                                $changedata['total_dividend'] = $junfen_danfenamount;
                                $changedata['md5log'] = $stage.$jc['jc_name']."：奖金池-均分分红：用户ID".$v."，分红金额:".$junfen_danfenamount."元。";
                                if($junfen_danfenamount > 0){
                                    $AccountModel->change($changedata, $v, false);
                                }
                            }
                        }
                    }
                    if($junfen_totalamount > $alljunfenamount){
                        $lastjunfenamount = $jc['total_amount']-$alljunfenamount;
                    }else{
                        $lastjunfenamount = $jc['total_amount']-$junfen_totalamount;
                    }
                    if($lastjunfenamount<=0){
                        $jc->save(['total_amount' => 0]);
                    }else{
                        $jc->save(['total_amount' => $lastjunfenamount]);
                    }
                }
            }

            //贡献值分红
            if($jc['is_gongzhi'] == 1){

                if($gongxian_totalamount > 10) {   //均分金额大于10才循环

                    //贡献值的所有用户
                    foreach ($users as $user) {

                        //直推几个代理
                        $pushCount = UsersModel::where(['role_id' => 1, 'pid' => $user['user_id']])->field('user_id')->count(); // 统计自己下面的直推代理数
                        $zhitui_daili_num = floor($pushCount);  //升级条件 直推几个代理

                        //满足条件则
                        if ($zhitui_daili_num >= $jc['zhituidailinum']) {
                            //团队代理数
                            $tuanduires = $this->getUserTuanduidailinum($user['user_id']);

                            if ($tuanduires >= $jc['tuanduidailinum']) {
                                $manzugxIds .= $user['user_id'] . ',';
                            }

                        }
                    }

                    //贡献值的所有用户
                    $gongzhiUserList = $manzugxIds.$ids;
                    $gongzhiUserListarr = explode(',',$gongzhiUserList);
                    //$totalgongzhiUser = count($gongzhiUserListarr);
                    $totalUser = count($gongzhiUserListarr);
                    $jisuanallgongzhiamount = 0;
                    //开始循环分钱
                    foreach ($gongzhiUserListarr as $k => $v) {
                        if($jisuanallgongzhiamount<$gongxian_totalamount) {
                            //查询用户的贡献值
                            $datemonth = intval(date('m')) - 1;
                            $gongxianzhi = $this->getUsergongxianzhi($v, $jc['level_id'], $datemonth);
                            $gongxianzhiAmount = floor(($gongxian_totalamount * $gongxianzhi));
                            $gongxianzhiallAmount = $gongxianzhiAmount - ($gongxianzhiAmount * 0.05); //扣除5%
                            $data = [
                                'jc_id' => $jc['level_id'],
                                'user_id' => $v,
                                'num' => 1,
                                'stage' => $stage,
                                'total_amount' => floor($gongxianzhiallAmount),
                                'additional' => 0,
                                'createtime' => time(),
                                'fenhongname' => $jc['jc_name'] . '-贡献值分红',
                            ];

                            $jisuanallgongzhiamount += $gongxianzhiAmount;

                            echo '用户：' . $this->getUserNamebyuid($v) . '  data:' . json_encode($data) . PHP_EOL;
                            if ($gongxianzhiAmount > 0) {
                                $distrigongxianzhires = $DistributionLogModel->insert($data);
                                if ($distrigongxianzhires) {
                                    $gongzhiallamount += $gongxianzhiAmount;

                                    $changedata['change_desc'] = $stage.$jc['jc_name']."：奖金池-贡献值分红：用户ID".$v."，分红金额:".$gongxianzhiAmount."元。";
                                    $changedata['change_type'] = 41;
                                    $changedata['by_id'] = 1;
                                    $changedata['from_uid'] = $v;
                                    $changedata['balance_money'] = $gongxianzhiAmount;
                                    $changedata['bean_value'] = 0;
                                    $changedata['total_dividend'] = $gongxianzhiAmount;
                                    $changedata['md5log'] = $stage.$jc['jc_name']."：奖金池-贡献值分红：用户ID".$v."，分红金额:".$gongxianzhiAmount."元。";
                                    if($gongxianzhiAmount > 0){
                                        $AccountModel->change($changedata, $v, false);
                                    }
                                }
                            }
                        }
                    }
                    if($gongxian_totalamount > $gongzhiallamount){
                        $lastgongzhiamount = $jc['total_amount']-$gongzhiallamount;
                    }else{
                        $lastgongzhiamount = $jc['total_amount']-$gongxian_totalamount;
                    }
                    if($lastgongzhiamount<=0){
                        $jc->save(['total_amount' => 0]);
                    }else{
                        $jc->save(['total_amount' => $lastgongzhiamount]);
                    }

                }

            }


            //计算份额分
            if($jc['is_fene'] == 1){
                if($gongxianfe_totalamount > 10) {   //金额大于10才分
                    foreach ($users as $user) {
                        //直推几个代理
                        $pushCount = UsersModel::where(['role_id' => 1, 'pid' => $user['user_id']])->field('user_id')->count(); // 统计自己下面的直推代理数
                        $zhitui_daili_num = floor($pushCount);  //升级条件 直推几个代理
                        //满足条件则
                        if ($zhitui_daili_num >= $jc['zhituidailinum']) {
                            //团队代理数
                            $tuanduires = $this->getUserTuanduidailinum($user['user_id']);
                            if ($tuanduires >= $jc['tuanduidailinum']) {
                                $manzufeIds .= $user['user_id'] . ',';
                            }
                        }
                    }

                    $danfeneamount = $gongxianfe_totalamount / $jc['allfennum'];
                    //贡献值的所有用户
                    $feneUserList = $manzufeIds . $ids;
                    $feneUserListarr = explode(',', $feneUserList);
                    $totalUser = count($feneUserListarr);
                    $jisuanallamount = 0;

                    //开始循环分钱
                    foreach ($feneUserListarr as $k => $v) {

                        $fepushCount = UsersModel::where(['pid' => $v])->where('role_id','in',[1,2])->field('user_id')->count();
                        $nums = floor($fepushCount / $jc['zhituidailibyjige']);  //获得几份份额
                        $num = intval($nums*$jc['zhituidailibyjifen']);

                        //后台设置附件份数
                        $users = Db::table("users")->field('additional_div')->where("user_id = ".$v)->find();
                        $additional_div = json_decode($users['additional_div'], true);
                        $additional_div = intval($additional_div[$jc['level_id']]['value']);
                        if($additional_div > 0){
                            $num = $num+$additional_div;
                        }
                        if(!$additional_div){
                            $additional_div = 0;
                        }

                        if($num>0 && $jisuanallamount<$gongxianfe_totalamount) {

                            //每份多少金额
                            $divAmount = bcmul($danfeneamount, $num);
                            $divAllmount = $divAmount - ($divAmount * 0.05); //扣除5%

                            $data = [
                                'jc_id' => $jc['level_id'],
                                'user_id' => $v,
                                'num' => $num,
                                'stage' => $stage,
                                'total_amount' => floor($divAllmount),
                                'additional' => $additional_div,
                                'createtime' => time(),
                                'fenhongname' => $jc['jc_name'].'-份额分红',
                            ];

                            $jisuanallamount += $divAmount;

                            echo '用户：' . $this->getUserNamebyuid($v) . '  data:' . json_encode($data) . PHP_EOL;

                            if ($divAllmount > 0) {

                                $distrifeneres = $DistributionLogModel->insert($data);
                                if($distrifeneres){
                                    $allfeneamount += $divAmount;

                                    $changedata['change_desc'] = $stage.$jc['jc_name']."：奖金池-份额分红：用户ID".$v."，分红金额:".$divAmount."元。";
                                    $changedata['change_type'] = 41;
                                    $changedata['by_id'] = 1;
                                    $changedata['from_uid'] = $v;
                                    $changedata['balance_money'] = $divAmount;
                                    $changedata['bean_value'] = 0;
                                    $changedata['total_dividend'] = $divAmount;
                                    $changedata['md5log'] = $stage.$jc['jc_name']."：奖金池-份额分红：用户ID".$v."，分红金额:".$divAmount."元。";
                                    if($divAmount > 0){
                                        $AccountModel->change($changedata, $v, false);
                                    }
                                }


                            }
                        }

                    }
                    //$jc->where(["level_id","=",$jc['level_id']])->save(['total_amount' => $jc['total_amount']-$allfeneamount]);

                    if($gongxianfe_totalamount > $allfeneamount){
                        $lastfeieamount = $jc['total_amount']-$gongxianfe_totalamount;
                    }else{
                        $lastfeieamount = $jc['total_amount']-$allfeneamount;
                    }
                    if($lastfeieamount<=0){
                        $jc->save(['total_amount' => 0]);
                    }else{
                        $jc->save(['total_amount' => $lastfeieamount]);
                    }
                }
            }
            $issueAmount = 0;
            $issueAmount = $alljunfenamount+$gongzhiallamount+$allfeneamount;
            if($issueAmount > $totalamountss){
                $issueAmount = $totalamountss;
            }

            $logData = [
                'total_amount' => $jc['total_amount'],
                'issue_amount' => $issueAmount,
                'total_copies' => intval($totalUser),
                'total_join_num' => intval($totalUser),
                'create_time' => time(),
                'stage' => $stage,
            ];

            Db::table('distribution_jc_execute_log')->insert($logData);
            echo '奖池：' . $jc['jc_name'] . '  data:' . json_encode($logData) . PHP_EOL;

        }
        echo "执行完成" . PHP_EOL;
        die;

    }

    /*
     * 获取用户名称
     */
    public function getUserNamebyuid($uid){
        if($uid == '' || empty($uid)){
            return '-';
        }else{
            $userObj = Db::table("users")->where("user_id = ".$uid)->find();
            return $userObj['user_name'];
        }
    }




    public function getusers(){
        //30683 顶级
        //$res = $this->getAllSub(30835);
        //$res = $this->getUnderlingUIds(30835);
        //$res = $this->getUnderlingnumUIds(30683);
        //$datemonth = intval(date('m')) -1;
        //echo date("Y:m:d h:i:s",1690542738);

        //$res = $this->getUsergongxianzhi(30835,1,$datemonth);
        //$res = $this->getUserTuanduidailinum(30683);
        /*

        $DividendInfo = settings('DividendInfo');
        $DividendSatus = settings('DividendSatus');
        $userModel = new \app\member\model\UsersModel();

        $this->userInfo['user_id'] = 3148;
        //根据注册时间最早的时间查3个下级用户
        $start_push_User = $userModel->where([
            ['pid', '=', $this->userInfo['user_id']],
            ['up_agent_time', '<>', ''],
        ])->order("up_agent_time asc")->limit(3)->select();


        $start_push_Usercount = $userModel->where([
            ['pid', '=', $this->userInfo['user_id']],
            ['up_agent_time', '<>', ''],
        ])->order("up_agent_time asc")->limit(3)->count();


        $manzugxIds = '';
        if ($start_push_Usercount > 0) {
            foreach ($start_push_User as $user){
                $manzugxIds .= $user['user_id'] . ',';
            }
            $pull_UserList = rtrim($manzugxIds,',');
        }else{
            $pull_UserList = '30000';
        }


        //$pull_UserList = rtrim($manzugxIds,',');

        $rebate_push_num = $userModel
            ->where([
                ['pid', '=', $this->userInfo['user_id']],
                ['role_id', '=', 2],
                ['user_id', 'in', $pull_UserList],
            ])
            ->count();
        */
        $user = UsersModel::where(['user_id' => 30683])->find();

        $additional_div = json_decode($user['additional_setapply'],true);
        if($additional_div || !empty($additional_div)){
            $nums = '';
            foreach ($additional_div as $k=>$v){
                foreach ($v as $kk=>$vv){
                    $nums += $vv;

                }

            }
        }
        echo $nums;

        dump($additional_div);


        dump($res);
    }

    /*
     * 计算用户贡献值
     * @author linkai
     * @return string 贡献值 百分百
     * $uid 当前团队用户id，$jc_id 奖池id  $datemonth 上个月月份
     */
    public function getUsergongxianzhi($uid,$jc_id,$datemonth){
        if($uid){
            //获得团队下面所有用户
            $AlluserArr = $this->getTeamLevelCount($uid,$jc_id,[]);
            $AlluserArr[] = $uid;

            $distribution_jc_log = new DistributionJcLog();
            $start_time = strtotime(date("Y-$datemonth-01 00:00:00"));
            $end_time  = strtotime(date("Y-$datemonth-t 23:59:59"));
            $where[] = ['jc_id','=',$jc_id];
            $where[] = ['user_id','in',$AlluserArr];
            if(!empty($datemonth) || $datemonth != ''){
                $where[] = ['createtime','>=' ,$start_time];
                $where[] = ['createtime','<=' ,$end_time];
            }

            $distribution_jc_logObj = $distribution_jc_log->where($where)->sum("enter_amount"); //该团队业绩（该用户）
//            dump($distribution_jc_log->getLastSql());
            //echo $distribution_jc_log->getLastSql();

            //计算传的月份奖金池总奖金
            $whereall[] = ['jc_id','=',$jc_id];
            if(!empty($datemonth) || $datemonth != '') {
                $whereall[] = ['createtime', '>=', $start_time];
                $whereall[] = ['createtime', '<=', $end_time];
            }
            $alldistribution_jc_logObj = $distribution_jc_log->where($whereall)->sum("enter_amount");


            //计算团队在总金额的比例  $distribution_jc_logObj/$alldistribution_jc_logObj;
            $bili = round($distribution_jc_logObj/$alldistribution_jc_logObj,4);
            if($bili>0){
                return $bili;
            }else{
                return 0;
            }
        }else{
            return 0;
        }
    }



    /**
     * 获取用户下属ID集合
     * @param $uid int
     * @param $ids string
     * @author linkai
     * @return string
     */
    public function getUnderlingUIds($uid, $ids='')
    {
        $userModel = new UsersModel();
        //$back = Db("users")->field('user_id')->where('pid',$uid)->select();
        $back = Db::table("users")->field('user_id')->where("pid = ".$uid)->select();  //user_id != 30683 and
        if (!empty($back) && is_array($back)) {
            foreach ($back as $v) {
                //防止当前人的ID重复去查询，形成恶性循环
                if ($v['user_id'] == $uid) {
                    continue;
                }
                //$back2 = Db("users")->where('pid',$v['user_id'])->count('user_id');
                //$back22 = $userModel->field('user_id')->where('pid',$v['user_id'])->select();
                $back22 = Db::table("users")->field('user_id')->where("pid = ".$v['user_id'])->select();
                if ($back22 > 0) {

                    $ids = $this->getUnderlingUIds($v['user_id'],$ids);
                    $ids .= ','.$v['user_id'];
                    foreach ($back22 as $vs) {
                        $ids .= ','.$vs['user_id'];
                    }
                } else {
                    $ids .= ','.$v['user_id'];
                }
            }
        }
        $ids = $uid.','.$ids.',';
        $ids = str_replace(',,', ",", $ids);
        $ids = trim($ids, ',');
        return $ids;
    }
    /**
     * 获取用户下属ID集合
     * @param $uid int
     * @param $ids string
     * @author linkai
     * @return string
     */
    public function getUnderLianChuangUIds($uid, $ids='',$jc_id)
    {
        $userModel = new UsersModel();
        //$back = Db("users")->field('user_id')->where('pid',$uid)->select();
        $back = Db::table("users")->field('user_id,additional_setapply')->where("pid = ".$uid)->select();  //user_id != 30683 and
        if (!empty($back) && is_array($back)) {
            foreach ($back as $v) {
                //防止当前人的ID重复去查询，形成恶性循环
                if ($v['user_id'] == $uid) {
                    continue;
                }
                if($v['additional_setapply']){
                    continue;
                }
                //$back2 = Db("users")->where('pid',$v['user_id'])->count('user_id');
                //$back22 = $userModel->field('user_id')->where('pid',$v['user_id'])->select();
                $back22 = Db::table("users")->field('user_id')->where("pid = ".$v['user_id'])->where('additional_setapply','<>',$jc_id)->select();
                if ($back22 > 0) {

                    $ids = $this->getUnderLianChuangUIds($v['user_id'],$ids,$jc_id);
                    $ids .= ','.$v['user_id'];
                    foreach ($back22 as $vs) {
                        $ids .= ','.$vs['user_id'];
                    }
                } else {
                    $ids .= ','.$v['user_id'];
                }
            }
        }
        $ids = $uid.','.$ids.',';
        $ids = str_replace(',,', ",", $ids);
        $ids = trim($ids, ',');
        return $ids;
    }

    /**
     * 所有下级ID
     * @param $user_id
     * @param $return_arr
     * @param int $check_promotion
     * @return mixed
     */
    public function getTeamLevelCount($user_id,$jc_id,$return_arr){
        $child_list = Db::name('users')->where(['pid' => $user_id])->select();
        if($child_list){
            foreach ($child_list as $val){
                if($val['additional_setapply'] == $jc_id){
                    continue;
                }
                $return_arr[] = $val['user_id'];
                $return_arr = self::getTeamLevelCount($val['user_id'],$jc_id,$return_arr);
            }
        }
        return $return_arr;
    }

    /*
     * 获取团队下面几个代理
     *
     */
    public function getUserTuanduidailinum($uid){
        $usersArray = $this->getUnderlingUIds($uid);
        $wheres[] = ["role_id" , "=" , 1];
        $wheres[] = ["user_id" , "in" ,$usersArray];
        $userModel = new UsersModel();
        $isdaili = $userModel->where($wheres)->count();
        //echo Db('users','',false)->getLastSql();

        return $isdaili;
    }

    /**
     * 获取用户团队下面几个代理  此方法废弃
     * @param $uid int
     * @param $ids string
     * @author linkai
     * @return string 用户下面团队的代理数量
     */
    public function getUnderlingnumUIds($uid, $ids='')
    {
        $nums = 0;
        $userModel = new UsersModel();
        $back = $userModel->field('user_id')->where('pid',$uid)->select();
        //$back = $userModel->field('user_id')->where("user_id != 30683 and pid = ".$uid)->select();
        if (!empty($back) && is_array($back)) {
            foreach ($back as $v) {
                //防止当前人的ID重复去查询，形成恶性循环
                if ($v['user_id'] == $uid) {
                    continue;
                }
                $back2 = $userModel->where('pid',$v['user_id'])->count('user_id');
                $back22 = $userModel->field('user_id')->where('pid',$v['user_id'])->select();
                if ($back2 > 0) {

                    $ids = $this->getUnderlingnumUIds($v['user_id'],$ids);
                    $ids .= ','.$v['user_id'];
                    foreach ($back22 as $vs) {
                        $ids .= ','.$vs['user_id'];
                    }
                } else {
                    $ids .= ','.$v['user_id'];
                }
            }
        }
        $ids = $uid.','.$ids.',';
        $ids = str_replace(',,', ",", $ids);
        $ids = trim($ids, ',');

        $idsarr = explode(',',$ids);
        $idsarr = array_unique($idsarr);

        $wheres[] = ["role_id" , "=" , 1];
        $wheres[] = ["user_id" , "in" ,$idsarr];
        //$isdaili = Db('users','',false)->field('user_id')->where($wheres)->count();
        //echo Db('users','',false)->getLastSql();

        foreach ($idsarr as $k=>$v){
            $isdaili = $userModel->field('user_id')->where("role_id = 1 and user_id = ".$v)->select();
            if($isdaili){
                $nums++;
            }

            //$newtuanduires = explode(",", $isdaili);
            //$newtuanduiress = array_unique($newtuanduires);
        }
        //return $isdaili;

        return $nums;
    }

    /*
     * 获取所有用户下面包含奖金池的用户
     */
    public function getUserByadditional(){
        $userModel = new UsersModel();
        $back = $userModel->where("additional_setapply != ''")->select();
        if($back){
            return $back;
        }else{
            return 0;
        }

    }




    /*------------------------------------------------------ */
    //-- 自定义商城首页
    /*------------------------------------------------------ */
    public function getIndexInfo()
    {
        $ShopPageTheme = new \app\shop\model\ShopPageTheme();
        $data['page'] = $ShopPageTheme->getToWxApp();
        return $this->success($data);
    }
    /*------------------------------------------------------ */
    //-- 自定义页页
    /*------------------------------------------------------ */
    public function getDiyPage()
    {
        $pageid = input('pageid', 0, 'intval');
        if ($pageid < 1) {
            return $this->error('传参错误.');
        }
        $ShopPageTheme = new \app\shop\model\ShopPageTheme();
        $data['page'] = $ShopPageTheme->getToWxApp($pageid);
        return $this->success($data);
    }
}
